package com.linkoog.devtools.json.file_editer.action;

import com.intellij.json.JsonFileType;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl;
import com.intellij.openapi.project.Project;
import com.intellij.testFramework.LightVirtualFile;
import com.linkoog.devtools.json.JsonEditerCricleNumber;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;

/**
 *  【console右键菜单】 显示 json 文本
 */
public class ShowJsonViewAction extends AnAction {


    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        Project project = event.getProject();
        if (project == null) return;

        String selectedText = getSelectedText(event);
        if (StringUtils.isNotBlank(selectedText)) return;

        String name = "temp-" +  JsonEditerCricleNumber.nextNumber() + ".json";
        LightVirtualFile lightVirtualFile = new LightVirtualFile(name, JsonFileType.INSTANCE, selectedText);

        FileEditorManager.getInstance(project).openFile(lightVirtualFile, true);
    }

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return ActionUpdateThread.BGT;
    }

    private String getSelectedText(AnActionEvent event){
        Editor editor = event.getData(LangDataKeys.EDITOR);
        if (editor == null)  return null;

        return editor.getCaretModel().getCurrentCaret().getSelectedText();
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        String selectedText = getSelectedText(event);
        Presentation presentation = event.getPresentation();
        presentation.setEnabledAndVisible(StringUtils.isNotBlank(selectedText));
    }

}
